import os

import time
import pandas as pd
from flask import request, send_from_directory
import rqdatac
from dash import get_app
from dash import (
    dcc,
    html,
    callback,
    Output,
    Input,
    State,
    register_page,
    MATCH,
    ctx,
)
import feffery_antd_components as fac

from ddbtools import BaseCRUD, DBDf, Filter, Comparator,get_table_columns
from gypb.db import get_db
from gypb.config import settings
from gypb.apps.weekly_reports import (
    generate_report
)
from gypb.component import DirFilesTable, CRUDTable
from xqdata_ddb import DDBDataApi
from pathlib import Path

api = DDBDataApi()

register_page(__name__, name="私募周月报", order=3)

# rqdatac.init(settings.rqdata.user,settings.rqdata.password)

basedir = settings.custom_dir
if not basedir:
    basedir = Path.home().joinpath(".gypb")

weekly_report_dir = Path(basedir).joinpath("weeklyreport")
if not os.path.exists(weekly_report_dir):
    os.makedirs(weekly_report_dir)
monthly_report_dir = Path(basedir).joinpath("monthlyreport")
if not os.path.exists(monthly_report_dir):
    os.makedirs(monthly_report_dir)

weekly_report_name = "weekly_report"
monthly_report_name = "monthly_report"
weekly_filetable = DirFilesTable(
    name=weekly_report_name,
    dir=str(weekly_report_dir),
    enable_delete=True,
    enable_download=True,
)
monthly_filetable = DirFilesTable(
    name=monthly_report_name,
    dir=str(monthly_report_dir),
    enable_delete=True,
    enable_download=True,
)

config_table_name = "weekly_monthly_reports"

config_table = CRUDTable(
    name=config_table_name,
    db_path="dfs://infos",
    table_name="weekly_monthly_reports",
    key_cols=["prod_code"],
    editable_cols=[
        "产品名称",
        "管理人名称",
        "成立日期",
        "策略类型",
        "二级策略类型",
        "对标基准",
        "代销范围",
        "纳入周报",
        "纳入月报",
    ],
)

strategy_order_table_name = "weekly_monthly_reports_strategy_order"

strategy_order_table = CRUDTable(
    name=strategy_order_table_name,
    db_path="dfs://infos",
    table_name="weekly_monthly_reports_strategy_order",
    key_cols=["strategy"],
    editable_cols=[
        "策略类型",
        "策略顺序",
    ],
)

def layout():
    return html.Div(
        [
            weekly_filetable.layout,
            fac.AntdButton(
                "生成周报", id={"type": "button", "index": weekly_report_name}, type="primary"
            ),           
            fac.AntdModal(
                id={"type": "modal", "index": weekly_report_name},
                title="生成周报",
                renderFooter=True,
                confirmAutoSpin=True,
                loadingOkText="生成周报中",
                okClickClose=False,
                children=[
                    fac.AntdCenter(
                        fac.AntdForm(
                            [
                                fac.AntdFormItem(
                                    fac.AntdDatePicker(id={"type": "date-selector", "index": weekly_report_name}),
                                    label="指定日期",
                                ),
                            ],
                            labelCol={"span": 6},
                            wrapperCol={"span": 18},
                            style={"width": 400},
                            id="form-new-weeklyreport",
                            enableBatchControl=True,
                            values={},
                        ),
                    )
                ],
            ),
            html.Div(
                id={"type": "notification", "index": weekly_report_name},
            ),

            monthly_filetable.layout,
            fac.AntdButton(
                "生成月报", id={"type": "button", "index": monthly_report_name}, type="primary"
            ),           
            fac.AntdModal(
                id={"type": "modal", "index": monthly_report_name},
                title="生成月报",
                renderFooter=True,
                confirmAutoSpin=True,
                loadingOkText="生成月报中",
                okClickClose=False,
                children=[
                    fac.AntdCenter(
                        fac.AntdForm(
                            [
                                fac.AntdFormItem(
                                    fac.AntdDatePicker(id={"type": "date-selector", "index": monthly_report_name}),
                                    label="指定日期",
                                ),
                            ],
                            labelCol={"span": 6},
                            wrapperCol={"span": 18},
                            style={"width": 400},
                            id="form-new-monthlyreport",
                            enableBatchControl=True,
                            values={},
                        ),
                    )
                ],
            ),
            html.Div(
                id={"type": "notification", "index": monthly_report_name},
            ),

            fac.AntdCollapse(
                config_table.layout,
                title='周报月报配置',
                isOpen=False,
                # style={'width': 300},
            ),
            fac.AntdCollapse(
                strategy_order_table.layout,
                title='策略显示顺序配置',
                isOpen=False,
                # style={'width': 300},
            ),            
        ]
    )


@callback(
    Output({"type": "modal", "index": MATCH}, "visible", allow_duplicate=True),
    Input({"type": "button", "index": MATCH}, "nClicks"),
    prevent_initial_call=True,
)
def modal_footer_demo(nClicks):
    return True


@callback(
    Output({"type": "dirfiles-table", "index": MATCH}, "data", allow_duplicate=True),
    Output({"type": "modal", "index": MATCH}, "confirmLoading"),
    Output({"type": "modal", "index": MATCH}, "visible", allow_duplicate=True),
    Output({"type": "notification", "index": MATCH}, "children", allow_duplicate=True),
    Input({"type": "modal", "index": MATCH}, "okCounts"),
    State({"type": "date-selector", "index": MATCH}, "value"),
    prevent_initial_call=True,
)
def handle_modal_generate_weeklyreport(okCounts, date):
    if okCounts:
        date = pd.Timestamp(date)
        
        trigger_id = ctx.triggered_id["index"]
        if trigger_id == weekly_report_name:
            generate_report(date,save_dir=weekly_report_dir,type='weekly')
            return (
                weekly_filetable.get_data(),
                False,
                False,
                fac.AntdNotification(
                    message="生成成功",
                    description=f"成功生成周报:{date}",
                    type="success",
                ),
            )
        else:
            generate_report(date,save_dir=monthly_report_dir,type='monthly')
            return (
                monthly_filetable.get_data(),
                False,
                False,
                fac.AntdNotification(
                    message="生成成功",
                    description=f"成功生成月报:{date}",
                    type="success",
                ),
            )